package com.share.thread;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Objects;

/**
 * @desc:
 * @author:caifan
 * @date:2022/4/6
 */
public class DeadLockDemo01 implements Runnable {

    private int flag = 1;

    private static Object obj1 = new Object();

    private static Object obj2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        DeadLockDemo01 lock1 = new DeadLockDemo01();
        DeadLockDemo01 lock2 = new DeadLockDemo01();
        lock1.flag = 1;
        lock2.flag = 2;
        new Thread(lock1).start();
        new Thread(lock2).start();
        Thread.sleep(3000);
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        if (Objects.nonNull(deadlockedThreads) && deadlockedThreads.length > 0) {
            for (long deadlockedThread : deadlockedThreads) {
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThread);
                System.out.println("线程id为"+threadInfo.getThreadId()+",线程名:" + threadInfo.getThreadName() + "的线程已经发生死锁，需要的锁正被线程" + threadInfo.getLockOwnerName()+"持有。");
            }
        }
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-flag = " + flag);
        if (flag == 1) {
            synchronized (obj1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj2) {
                    System.out.println("t1持有2把锁");
                }
            }
        }
        if (flag == 2) {
            synchronized (obj2) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj1) {
                    System.out.println("t2持有2把锁");
                }
            }
        }
    }
}
